import base64, json, time, hashlib
from datetime import datetime

if __name__ == '__main__':
    # 头部 header
    header_data = {
        "typ": "jwt",  # 声明token类型
        "alg": "HS256",  # 声明签证的加密算法
    }

    # # 将字典 header_data 转换为 JSON 字符串并进行 UTF-8 编码
    # x = json.dumps(header_data).encode()
    # # 对编码后的 JSON 字符串进行 Base64 编码
    # x2 = base64.b64encode(x)
    # # 将 Base64 编码后的字节解码为字符串
    # header = x2.decode()
    # print(header)

    header = base64.b64encode(json.dumps(header_data).encode()).decode()
    print(header)

    # 载荷 payload
    # 标准声明，公共声明，私有声明
    # 标准声明
    # iss: jwt签发者
    # sub: jwt所面向的用户

    #   **常用**
    #   aud: 接受jwt的一方
    #   exp: jwt过期时间
    #   nbf: 定义在什么时间之后，jwt才能使用
    #   iat: jwt签发时间
    #   jti: jwt的唯一身份标识，主要作为一次性token，从而回避重放攻击

    iat = time.time()
    payload_data = {
        "sub": "root",
        "exp": iat + 3600,  # 假设一小时过期
        "iat": iat,
        "name": "gqt",
        "avatar": "1.png",
        "user_id": 1,
        "admin": True,
        "acc_pwd": "QiLCJhbGciOiJIUzI1NiJ9QiLCJhbGciOiJIUzI1NiJ9QiLCJhbGciOiJIUzI1NiJ9",
    }

    payload = base64.b64encode(json.dumps(payload_data).encode()).decode()
    print(payload)
    # print(payload.encode(),1)

    secret = 'django-insecure-aihu7%=9pce99mi6r)5o_^+$3a+t@hi0@z4gk-t!-wz75a)19q'  # 服务器密钥 一定不能泄露
    data = header + payload + secret

    # 使用hashlib创建一个 SHA256 对象
    HS256 = hashlib.sha256()
    # 更新对象，将数据转化为utf-8编码后添加到对象中
    HS256.update(data.encode('utf-8'))
    # 获取HS256的十六进制哈希值
    signature = HS256.hexdigest()
    print(signature)

    # 最终token
    token = f"{header}.{payload}.{signature}"
    print(token)

    token = "eyJ0eXAiOiAiand0IiwgImFsZyI6ICJIUzI1NiJ9.eyJzdWIiOiAicm9vdCIsICJleHAiOiAxNzIzNzExMzczLjExODMzMTcsICJpYXQiOiAxNzIzNzA3NzczLjExODMzMTcsICJuYW1lIjogImdxdCIsICJhdmF0YXIiOiAiMS5wbmciLCAidXNlcl9pZCI6IDEsICJhZG1pbiI6IHRydWUsICJhY2NfcHdkIjogIlFpTENKaGJHY2lPaUpJVXpJMU5pSjlRaUxDSmhiR2NpT2lKSVV6STFOaUo5UWlMQ0poYkdjaU9pSklVekkxTmlKOSJ9.d87ec7468979b71bb30f2bb2e6a68be65779065b50a2b36374536865d43c6b8d"
    header, payload, signature = token.split('.')

    # 验证是否过期
    payload_data = json.loads(base64.b64decode(payload.encode()))
    exp = payload_data.get('exp', None)
    if exp is not None and int(exp) < int(datetime.now().timestamp()):
        print("token过期")
    else:
        print("没有过期")

        secret = 'django-insecure-aihu7%=9pce99mi6r)5o_^+$3a+t@hi0@z4gk-t!-wz75a)19q'  # 服务器密钥 一定不能泄露
        data = header + payload + secret
        HS256 = hashlib.sha256()
        HS256.update(data.encode('utf-8'))
        new_signature = HS256.hexdigest()

        if new_signature != signature:
            print("认证失败")
        else:
            print("认证成功")
